import React, { Component } from 'react';
import { Button, Form, Icon, Input, message } from 'antd';
import expenseService from 'containers/my-account/expense.service';
import 'styles/my-account/components/expense-change.scss';
import { messages } from 'share/common';

class ExpenseChangeText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editStatus: false,
      editValue: props.field.value,
      allLoading: false
    };

  }

  // 编辑
  handleEdit = () => {
    let { editStatus, editValue } = this.state;
    const { value } = this.props.field;
    if (editStatus) {
      editValue = value;
    }
    editStatus = !editStatus;
    this.setState({ editStatus, editValue });
  };

  // 保存
  handleSave = () => {
    let { field } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (values[field.fieldOID] === field.value) {
          this.setState({ editStatus: false });
        } else {
          this.handleSaveText(values[field.fieldOID]);
        }
      }
    });

  };

  handleSaveText = (changedValues) => {
    let { invoiceOID, expenseReportOID, field } = this.props;
    let { editStatus, editValue } = this.state;
    let data = [];
    data.push({ value: changedValues, fieldOID: field.fieldOID });
    const params = { invoiceOID, expenseReportOID, data };
    let save = () => {
      expenseService.editTextFields(params)
        .then(() => {
          editStatus = false;
          message.success(messages('common.operate.success')/*操作成功*/);
          field.value = changedValues;
          editValue = changedValues;
          this.props.onChange(field);
        })
        .catch(err => {
          message.error(`${messages('common.operate.filed'/*操作失败*/)}，${errorMessage(err.response)}`);
        })
        .finally(() => {
          this.setState({ allLoading: false, editStatus, editValue });
        });
    };
    this.setState({ allLoading: true }, save());
  };


  // 取消
  handleCancel = () => {
    this.handleEdit();
  };

  render() {
    const { editStatus, editValue, allLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { field, readonly } = this.props;
    return (
      <section className="expense-change">
        <div className="expense-change-content">
          {
            editStatus
              ? <Form.Item>
                {getFieldDecorator(`${field.fieldOID}`, {
                  rules: [
                    {
                      required: field.required,
                      message: messages('common.name.is.required', { name: field.name })
                    },
                    {
                      max: 50,
                      message: messages('common.max.characters.length', { max: 50 })
                    }],
                  initialValue: editValue
                })(<Input/>
                )}
              </Form.Item>
              : <div>{editValue || '-'}{!readonly && <Icon className="expense-edit-icon" type="edit" onClick={this.handleEdit}/>}</div>
          }
        </div>
        {
          editStatus &&
          <div className="expense-change-footer">
            <Button
              className="footer-change-button"
              loading={allLoading}
              onClick={this.handleSave}
              type="primary"> {messages('common.save') /*保存*/}</Button>
            <Button
              className="footer-change-button"
              loading={allLoading}
              onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        }
      </section>);
  }
}

ExpenseChangeText.propTypes = {
  invoiceOID: React.PropTypes.string,
  expenseReportOID: React.PropTypes.string,
  field: React.PropTypes.object,
  onChange: React.PropTypes.func
};
const WrappedExpenseChangeText = Form.create()(ExpenseChangeText);
export default WrappedExpenseChangeText;
